# -*- coding: UTF-8 -*-

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from system.Email import SendMail

import pytesseract
from PIL import Image, ImageEnhance


class WebData:
    cfg_dic = ''
    browser = None

    # 配置环境变量
    pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
    tessdata_dir_config = '--tessdata-dir "C:/Program Files (x86)/Tesseract-OCR/tessdata"'

    # 邮件发送服务
    sendMail = None

    def __init__(self, config):
        self.cfg_dic = config
        self.sendMail = SendMail(config)
        # 打开浏览器
        self.login_url = "https://yz.chsi.com.cn/apply/cjcx/t/" + self.cfg_dic['报考单位代码'] + ".dhtml"
        self.browser = webdriver.Chrome()

    def isElementExist(self, element):
        flag = True
        try:
            self.browser.find_element_by_name(element)
            return flag
        except:
            flag = False
        return flag

    def getWebData(self):

        # 如果界面被人为结束，此处重新打开
        try:
            self.browser.get(self.login_url)
        except Exception as e:
            self.browser = webdriver.Chrome()
            self.browser.get(self.login_url)

        # 显式等待网页加载完成 “https://blog.csdn.net/weixin_42081389/article/details/98486562”
        try:
            element = WebDriverWait(self.browser, 5).until(
                EC.presence_of_element_located((By.NAME, 'yzwb_ksbh'))
            )
        except Exception as e:
            print(e)

        try:
            # 检查验证码是否存在
            if self.isElementExist(element="yzwb_checkcode"):
                # 保存到本地
                f = open('checkCode.html', mode="w", encoding="utf-8")
                f.write(self.browser.page_source)
                f.close()
        except Exception as e:
            print(e)
            return False

        try:
            # 姓名
            self.browser.find_element_by_name("yzwb_xm").send_keys(self.cfg_dic['考生姓名'])
            # 身份证号
            self.browser.find_element_by_name("yzwb_zjhm").send_keys(self.cfg_dic['身份证号'])
            # 考生编号
            self.browser.find_element_by_name("yzwb_ksbh").send_keys(self.cfg_dic['考生编号'])
            # 检查验证码是否存在、处理验证码
            if self.isElementExist(element="yzwb_checkcode"):
                print("处理验证码")
                # 窗口最大化
                # self.browser.maximize_window()
                # 获取图像验证码位置、大小
                imgelement = self.browser.find_element_by_xpath('//*[@id="app"]/div/form[2]/div[5]/div/div[2]/img')
                location = imgelement.location
                size = imgelement.size
                rangle = (
                    int(location['x']), int(location['y']), int(location['x'] + size['width']),
                    int(location['y'] + size['height'])
                )

                # 截取网页
                self.browser.get_screenshot_as_file('./img/image1.png')  # 比较好理解
                # 等待保存
                # time.sleep(1)
                # 重新裁剪，获取验证码
                im = Image.open('./img/image1.png')
                region = im.crop(rangle)  # 此时，region是一个新的图像对象
                region.save("./img/code1.png")

                # time.sleep(1)

                # 验证码二值化、对比度加强
                im = Image.open("./img/code1.png")
                imgry = im.convert('L')  # 图像加强，二值化
                sharpness = ImageEnhance.Contrast(imgry)  # 对比度增强
                sharp_img = sharpness.enhance(2.0)
                sharp_img.save("./img/code2.png")

                # 去除验证码多余空格
                code = pytesseract.image_to_string(sharp_img).replace(' ', '')
                code = code.replace('.', '')
                code = code.replace(':', '')
                self.browser.find_element_by_name("yzwb_checkcode").send_keys(code)
                print(code)

                # 提交
                self.browser.find_element_by_xpath("//*[@id='app']/div/form[2]/div[6]/div/button").click()
                # 窗口最小化
                # self.browser.minimize_window()
            else:
                # 提交,
                self.browser.find_element_by_xpath("//*[@id='app']/div/form[2]/div[5]/div/button/span").click()
        except Exception as e:
            return False

        # 等待网页加载完成
        time.sleep(2)

        # 可能需要在学信网查询 https://yz.chsi.com.cn/apply/cjcxa/
        try:
            # 身份证号
            self.browser.find_element_by_name("username").send_keys(self.cfg_dic['身份证号'])
            # 考生编号
            self.browser.find_element_by_name("password").send_keys(self.cfg_dic['密码'])
            # 提交
            self.browser.find_element_by_name("submit").click()
        except Exception as e:
            print(e)
            return False

        # 保存查询结果
        try:
            if self.browser.find_element_by_xpath('/html/body/div[1]/div[3]/div[1]/table/tbody/tr[1]/td[1]'):
                self.browser.maximize_window()
                self.browser.save_screenshot("./img/result.png")
                print("[查询时间：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "][查询成功]")
                # 保存到本地
                f = open('result.html', mode="w", encoding="utf-8")
                f.write(self.browser.page_source)
                f.close()

                # 发送网站代码到邮箱
                self.sendMail.send_Email()
                return True

            else:
                print("[查询时间：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "][成绩未上传]")
                # 邮箱测试
                if self.cfg_dic['邮箱测试'] == "True":
                    self.browser.maximize_window()
                    self.browser.save_screenshot("./img/result.png")
                    print("[测试模式，本次查询结果将发送到邮箱]")
                    # 保存到本地
                    f = open('result.html', mode="w", encoding="utf-8")
                    f.write(self.browser.page_source)
                    f.close()

                    # 发送网站代码到邮箱
                    self.sendMail.send_Email()
                    self.browser.minimize_window()
                return False

        except Exception as e:
            print("错误")
            print(e)
            return False

    def getResult(self):
        while True:
            if self.getWebData():
                # 如果查询到成绩，退出查询任务
                return
            else:
                # 最短30秒的延时
                ti = 30
                if (int(self.cfg_dic['分钟延时'])) * 60 > 0:
                    ti = (int(self.cfg_dic['分钟延时'])) * 60
                print("开始延时：", ti, " 秒")
                time.sleep(ti)
